package com.sdk.apiNotify.rabbitmq.consumber.handle;

import com.coment.dto.ApiNotify;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import com.sdk.apiNotify.rabbitmq.consumber.server.ApiNotifyPushService;
import com.sdk.apiNotify.rabbitmq.producer.ApiNotifyProducer;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class ApiNotifyRetryHandle implements ChannelAwareMessageListener {
   @Resource
   private ApiNotifyProducer apiNotifyProducer;
   @Resource
   private ApiNotifyPushService apiNotifyPushService;

   public void onMessage(Message message, Channel channel) throws Exception {
      ObjectMapper mapper = new ObjectMapper();
      ApiNotify apiNotify = mapper.readValue(message.getBody(), ApiNotify.class);
      Integer retryCount = apiNotify.getRetryCount();
      retryCount = retryCount + 1;

      try {
         log.warn("第 {} 次重试 {}", retryCount, apiNotify);
         this.apiNotifyPushService.handlerMessage(apiNotify);
      } catch (Exception var7) {
         apiNotify.setRetryCount(retryCount);
         if (retryCount < 3) {
            this.apiNotifyProducer.sendToRetryQueueWithHeaders(apiNotify);
         } else {
            this.apiNotifyProducer.sendToDeadLetterQueue(apiNotify);
         }
      }

   }
}
